import App from './App'

// #ifndef VUE3
import Vue from 'vue'
Vue.config.productionTip = false
App.mpType = 'app'

import uView from '@/uni_modules/uview-ui'
Vue.use(uView);
import common from '@/libs/common.js';
Vue.prototype.$noMultipleClicks = common.noMultipleClicks;
import myRequest from "./libs/request.js";
Vue.prototype.$api = myRequest;
import config from '@/libs/config.js';
Vue.prototype.$url = config;
Vue.prototype.$img = function(url) {
	if (url) {
		var str = url.indexOf('uploads') == -1 ? '/uploads/' + url : url;
		var final_url = str.indexOf('http') == -1 ? config.baseUrl + str : str;
		return final_url;
	}
}
Vue.prototype.$to = function(url) {
	if (url) {
		uni.navigateTo({
			url
		});
	}
}
Vue.prototype.$back = function() {
	uni.navigateBack();
}
Vue.prototype.$date = function(num) {
	function add(m) {
		return m < 10 ? '0' + m : m;
	}
	if(num.toString().length != 13) {
		num = parseInt(num) * 1000
	}
	
	var time = new Date(num);
	var y = time.getFullYear();
	var m = time.getMonth() + 1;
	var d = time.getDate();
	return y + '-' + add(m) + '-' + add(d);
}
Vue.prototype.$tel = function(tel) {
	var reg1 = /^[1][3,4,5,7,8,9][0-9]{9}$/
	if (!tel) { //判断如果手机号为空，提示用户输入手机号
		// uni.showToast({
		// 	title: '请输入手机号',
		// 	icon: 'none'
		// })
		return '暂无';
	} else if (!reg1.test(tel)) { //判断手机号格式时候正确
		// uni.showToast({
		// 	title: '请输入正确的手机号',
		// 	icon: 'none'
		// })
		return tel;
	} else {
		var reg = /^(\d{3})\d{4}(\d{4})$/;
		var str = tel.replace(reg, '$1****$2');
		return str;
	}
},
Vue.prototype.toast = function(msg = '',icon = 'none', callback = () => {}) {
	if(msg || icon != 'none') {
		uni.showToast({
			title: msg,
			icon,
			mask: true,
			duration: 2000,
			success: callback
		});
	}
}
Vue.prototype.$upload = function(n) {
	let that = this;
	uni.chooseImage({
		sourceType: ['album','camera'], 
		success: res => {
			uni.showLoading()
			const tempFilePaths = res.tempFilePaths;
			const files = res.tempFiles;
			let imgArr = [];
			for (let i = 0; i < files.length; i++) {
				uni.uploadFile({
					url: `${config.baseUrl}uploadimgs`, //仅为示例，非真实的接口地址
					filePath: tempFilePaths[i],
					name: 'file',
					header: {
						"Authorization": uni.getStorageSync('token'),
					},
					success: (uploadFileRes) => {
						let data = JSON.parse(uploadFileRes.data);
						if(data.status == 1001) {
							uni.showModal({
								title: '温馨提示',
								content: '您暂未登陆或登录已失效，是否前往登录？',
								confirmText: '去登录',
								cancelText: '取消',
								success: (sv) => {
									if(sv.confirm) {
										uni.navigateTo({
											url: '/pages/login/login'
										})
									}
								}
							});
							uni.hideLoading();
							return false;
						}
						uni.hideLoading();
						that[n].push(data.data[0]);
					},
					fail: (err) => {
						uni.hideLoading();
					}
				});
			}
		}
	});
}
// 拦截器
uni.addInterceptor('request', {
	success(args) {
		// console.log('拦截器', args, 111122222);
		if(args.data.code === -1) {
			uni.showModal({
				title: '温馨提示',
				content: '暂未授权或授权信息已过期,是否获取授权？',
				success(e) {
					uni.removeStorageSync('token');
					if(e.confirm) {
						uni.reLaunch({
							url: `/pages/login/login`
						})
					}
				}
			})
		}
	}
})


try {
  function isPromise(obj) {
    return (
      !!obj &&
      (typeof obj === "object" || typeof obj === "function") &&
      typeof obj.then === "function"
    );
  }

  // 统一 vue2 API Promise 化返回格式与 vue3 保持一致
  uni.addInterceptor({
    returnValue(res) {
      if (!isPromise(res)) {
        return res;
      }
      return new Promise((resolve, reject) => {
        res.then((res) => {
          if (res[0]) {
            reject(res[0]);
          } else {
            resolve(res[1]);
          }
        });
      });
    },
  });
} catch (error) { }

const app = new Vue({
  ...App
})
app.$mount()
// #endif

// #ifdef VUE3
import { createSSRApp } from 'vue'
export function createApp() {
  const app = createSSRApp(App)
  return {
    app
  }
}
// #endif